package com.aaa.controller;

import com.aaa.entity.Menu;
import com.aaa.entity.User;
import com.aaa.service.MenuService;
import com.aaa.service.UserService;
import com.aaa.util.Upload;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

@Controller
public class LoginController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private UserService userService;
    @Autowired
    private Upload upload;
    @RequestMapping("/login")
    public String login() {
        return "login/login";
    }

    @RequestMapping("/checkUser")
    public String checkUser(User user, Model model, HttpSession session) {
//        System.out.println(user.getUsername());
//        System.out.println(user.getPassword());
        User dbUser = userService.checkUser(user);
        if (dbUser == null) {
            return "error";
        } else {
            //往session中放置用户对象
            session.setAttribute("SESSION_USER", dbUser);
            //获取id 根据id 查询用户能操作的所有菜单
            List<Menu> menus = menuService.listMyMenus(dbUser.getUid());
            //获取用户所有能操作的所有的二级菜单的路径 放到session中
            List<String> twoMenuPaths = menuService.convertMenus(menus);
            //System.out.println(twoMenuPaths);
            //把用户能操作的菜单放到session中
            session.setAttribute("PERMITS", twoMenuPaths);
            //把menus传递搭配jsp界面
            model.addAttribute("menus", menus);
            return "index";
        }
    }

    @RequestMapping("/listMyMenus")
    @ResponseBody
    public List<Menu> listMyMenus(HttpSession session) {
        User user = (User) session.getAttribute("SESSION_USER");
        //获取用户id 根据用户id 查询用户能操作的所有菜单
        List<Menu> menus = menuService.listMyMenus(user.getUid());
        return menus;
    }

    /**
     * 查询用户能操作的所有菜单
     *
     * @return
     */
    @RequestMapping("/listMiniUiMenus")
    @ResponseBody
    public Map<String, Object> listMiniUiMenus(HttpSession session) {
        User user = (User) session.getAttribute("SESSION_USER");
        //获取用户id 根据用户id 查询用户能操作的所有菜单
        Map<String, Object> map = menuService.listMiniUiMenus(user.getUid());
        return map;
    }

    @RequestMapping("/byUid")
    public String byUid(Long uid, Model model) {
        try {
            User user = userService.byUid(uid);
            model.addAttribute("user", user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "login/user-setting";
    }

}

